'use strict';

layui.define(['layer', 'element', 'form', 'table', 'Vue', '$http', 'zmnUtils'], function (exports) {
    var $ = layui.$;
    var element = layui.element;
    var form = layui.form;
    var table = layui.table;
    var $http = layui.$http;
    var Vue = layui.Vue;
    var zmnUtils = layui.zmnUtils;

    var priceInTableVM = null;
    var priceOutTableVM = null;

    var categCache = [];

    var PRODUCT_LIST = '/serv/bycategid/product/list';
	var CATEG_LIST_URL = '/serv/categ/list';

	var PRODUCT_DATA_URL = '/work/price/fault/detail.action';

    function addCategCache (data) {
        data.forEach(function (item) {
            categCache.push(item);
        });
    }

    function getCategFromCategCache (categId) {
        return categCache.find(function (item) {
            return item.categId === categId;
        });
    }

	function fetchCategList (servCategId, productShowType) {
		return $http.get(CATEG_LIST_URL, {
			servCategId: servCategId,
			productShowType: productShowType
		}).done(function (data) {
			addCategCache(data)
		})
	}

	function fetchProductList (cityId, channelId, servCategId, categId, productShowType) {
		return $http.get(PRODUCT_LIST, {cityId, channelId, servCategId, categId, productShowType})
    }

    /**
     * 获取价格表数据
     * @param cityId
     * @param channelId
     * @param productId
     * @returns {*}
     */
    function fetchPriceData ({ cityId, channelId, productId, brandId }) {
        return $http.get(PRODUCT_DATA_URL, { cityId, channelId, productId, brandId });
    }

	var initCategList = (function () {
		var FULL_CLASS = 'data-full'

		return function (servCategId, productShowType) {
			var $tabItem = $('.layui-tab-item[data-id="' + servCategId + '"]')

			if ($tabItem.hasClass(FULL_CLASS)) {
				return
			}

			fetchCategList(servCategId, productShowType).then(function (data) {
				addCategCache(data)
				$tabItem.addClass(FULL_CLASS)
				var htmlStrArr = ['<div class="layui-btn-container">']

				data.forEach(function (item) {
					htmlStrArr.push('<button class="layui-btn btn-categ" lay-submit data-serv="' + servCategId + '" data-categ="' + item.categId + '">' + item.name + '</button>')
				})

				htmlStrArr.push('</div>')

				$tabItem.html(htmlStrArr.join(''))
			}, function (msg) {
				layer.msg(msg, {icon: 2})
			})
		}
	})()

    var handleProductBtnClick = (function () {
        var PRODUCT_DATA_URL = '/work/price/fault/detail.action';

        function fetchPriceData (productId, cityId) {
            var bizType = $('#bizType').val();
            var channelId = $('#channelId').val();
            return $http.get(PRODUCT_DATA_URL, { productId, cityId, bizType, channelId });
        }

        return function (categId, productId, cityId) {
            fetchPriceData(productId, cityId).then(function (data) {
                var categ = getCategFromCategCache(categId);
                var descStr = categ ? categ.desc || '' : '';
                data.desc = descStr ? descStr.split('\n') : [];
                priceTableVM.$set(priceTableVM.$data, 'priceData', data);
                layer.closeAll();
            }, function (msg) {
                layer.msg(msg, { icon: 2 });
            });
        }
    })();

    function initPriceTableByVUE (selector, title) {
        var vm = new Vue({
            el: selector,
            template: `<table class="table-price">
                <caption>{{ priceData.productName || '价格表' }}（{{ title }})</caption>
                <thead><tr><th>故障分组</th><th>故障项目</th><th>故障类型</th><th>价格</th></tr></thead>
                <tbody>
                    <template v-for="(group, index) in priceData.priceList">
                        <template  v-for="(item, i) in group.faultItems">
                            <tr v-if="i === 0">
                                <td :rowspan="group.faultItems.length">{{ group.groupName }}</td>
                                <td>{{ item.name }}</td>
                                <td>{{ item.typeName }}</td>
                                <td>{{ item | priceFormater }}</td>
                            </tr>
                            <tr v-else>
                                <td>{{ item.name }}</td>
                                <td>{{ item.typeName }}</td>
                                <td>{{ item | priceFormater }}</td>
                            </tr>
                        </template>
                    </template>
                    <tr class="none" v-if="!priceData.priceList || !priceData.priceList.length"><td colspan="4">暂无价格数据</td></tr>
                </tbody>
                <tfoot v-if="priceData.desc">
                    <tr>
                        <td colspan="3">
                            <p>服务说明：</p>
                            <p v-for="item in priceData.desc">{{ item }}</p>
                        </td>
                    </tr>
                </tfoot>
            </table>`,
            filters: {
                priceFormater: function (item) {
                    var formaterStr;
                    if (item.price == null) {
                        formaterStr = '面议';
                        if (item.negotiableMinPrice && item.negotiableMaxPrice) {
                            formaterStr = formaterStr + "(" + zmnUtils.unit.fenToYuan(item.negotiableMinPrice) + '元~' + zmnUtils.unit.fenToYuan(item.negotiableMaxPrice) + "元)";
                        } else if (item.negotiableMinPrice) {
                            formaterStr = formaterStr + "(最低价：" + zmnUtils.unit.fenToYuan(item.negotiableMinPrice) + '元)';
                        } else if (item.negotiableMaxPrice) {
                            formaterStr = formaterStr + "(最高价：" + zmnUtils.unit.fenToYuan(item.negotiableMaxPrice) + '元)';
                        }
                    } else {
                        formaterStr = (item.price / 100).toFixed(2) + `元/${item.unit}`;
                    }

                    return  formaterStr;
                }
            },
            data: function () {
                return {
                    priceData: {},
                    title: title
                };
            }
        });

        return vm;
    }



    function initSelectFactory (selector) {
        function createOptionForSelect (data) {
            data =  data.map(function (item) {
                return `<option value="${ item.value }">${ item.text }</option>`;
            });
            data.unshift('`<option value="">全部</option>`');
            return data.join('');
        }

        return function (data) {
            let options = createOptionForSelect(data);
            $(selector).html(options);
            form.render('select');
        }
    }

    var initCategSelect = initSelectFactory('#categId');
    var initProductSelect = initSelectFactory('#productId');

    function initPriceTable ({ priceListIn, priceListOut }, categId) {
        var categ = getCategFromCategCache(categId);
        var descStr = categ ? categ.desc || '' : '';
        if (priceListIn && priceListIn.length) {
            priceListIn.desc = descStr ? descStr.split('\n') : [];
        }
        if (priceListOut && priceListOut.length) {
            priceListOut.desc = descStr ? descStr.split('\n') : [];
        }
        priceInTableVM.$set(priceInTableVM.$data, 'priceData', priceListIn);
        priceOutTableVM.$set(priceOutTableVM.$data, 'priceData', priceListOut);
    }

    function  initPage () {
        priceInTableVM = initPriceTableByVUE('#zmn-price-fault-in', '保内');
        priceOutTableVM = initPriceTableByVUE('#zmn-price-fault-out', '保外');
    }

    function initEvent () {
        form.on('select(select-city)', function (data) {
            initProduct();
        });
        form.on('select(select-channel)', function (data) {
            initProduct();
        });
        form.on('select(select-servCateg)', function (data) {
            initCateg();
        });

		form.on('select(select-categ)', function (data) {
		    initProduct();
		});

		form.on('select(select-productShowType)', function (data) {
            initCateg();
		});

        form.on('submit()', function (data) {
            var categId = +data.field.categId;

            fetchPriceData(data.field).then(function (data) {
                initPriceTable(data, categId);
            });

            return false;
        });
    }

    function initProduct() {
        var categId = $('select[name="categId"]').val();
        var servCategId = $('select[name="servCategId"]').val();
        var productShowType = $('select[id="productShowType"]').val();
        var cityId = $('select[id="select-city"]').val();
        var channelId = $('select[id="channelId"]').val();
        initProductSelect([]);

        if (cityId && channelId && categId && servCategId) {
            fetchProductList(cityId, channelId, servCategId, categId, productShowType).then((data) => {
                data = data.map(function (item) {
                    return {
                        value: item.value,
                        text: item.text
                    }
                })

                initProductSelect(data)
            })
        }
    }
    function initCateg() {
        var productShowType = $('select[id="productShowType"]').val();
        var servCategId = $('select[name="servCategId"]').val()

        initCategSelect([]);
        initProductSelect([]);

        if (productShowType && servCategId) {
            fetchCategList(servCategId,productShowType).then((data) => {
                data = data.map(function (item) {
                    return {
                        value: item.value,
                        text: item.text
                    }
                });
                initCategSelect(data);
            });
        }
    }

    function init () {
        initPage();
        initEvent();
    }

    init();
    exports('zmn_oms_price_fault_list');
});
